/*
Copyright 2008, Mark Arvidson

This file is part of EwaScorecard.

EwaScorecard is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

EwaScorecard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with EwaScorecard.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;

public class MeetForm extends Form implements CommandListener, ItemStateListener {

    private TextField meetName = new TextField("Name", null, 25, TextField.ANY);
    private DateField meetDate = new DateField("Date", DateField.DATE);
    private TextField eventCountField = new TextField("How many Events? ", "6", 3, TextField.NUMERIC);
    private Command backCommand = new Command("Cancel", Command.BACK, 1);
    private Command okCommand = new Command("OK", Command.OK, 0);
    private Command loadCommand = new Command("Load", Command.SCREEN, 2);
    private Command alertOverwriteCommand = new Command("Yes", Command.OK, 0);
    private Command alertCancelCommand = new Command("No", Command.CANCEL, 0);
    private MeetData meetData;
    private EwaScorecard host;
    private int fields;
    private String[] defaultEventNames = new String[]{"FX", "PH", "SR", "V ", "PB", "HB"};
    private Vector defaultTeams;

    public MeetForm(EwaScorecard host, MeetData meetData) {
        super("Meet Info");
        this.host = host;
        meetDate.setDate(new Date());
        append(meetName);
        append(meetDate);
        append(eventCountField);
        if (meetData != null) {
            addCommand(backCommand);
        }
        addCommand(okCommand);
        addCommand(loadCommand);
        setCommandListener(this);
        setItemStateListener(this);
        loadDefaults(meetData);
    }

    public void itemStateChanged(Item item) {
        if (item == eventCountField) {
            setEventLabels();
        }
    }

    private void createMeet() throws NumberFormatException {

        int eventCount = Integer.parseInt(eventCountField.getString());
        if (eventCount > 0) {
            String[] eventNames = new String[eventCount];
            for (int i = 0; i < eventCount; i++) {
                eventNames[i] = ((TextField) get(i + 3)).getString();
            }
            MeetData newMeet = new MeetData(meetName.getString(), meetDate.getDate(), eventCount, eventNames);
            if (defaultTeams != null) {
                Enumeration teamEnum = defaultTeams.elements();
                while (teamEnum.hasMoreElements()) {
                    TeamData team = (TeamData) teamEnum.nextElement();
                    newMeet.teams().addElement(team.clone());
                }
            }
            host.setMeetData(newMeet);
        }
    }

    private void loadDefaults(MeetData defaults) {
        try {
            if (defaults == null) {
                RecordStore.openRecordStore(EwaScorecard.DEFAULTS_RECORD_NAME, false);
                try {
                    defaults = MeetData.retrieveRecord(EwaScorecard.DEFAULTS_RECORD_NAME);
                } catch (RecordStoreFullException e) {
                    Alert alert = new Alert("Could not load", "Out of memory", null, AlertType.ERROR);
                    Display.getDisplay(host).setCurrent(alert);
                } catch (Exception ex) {
                    Alert alert = new Alert("Could not load", ex.getMessage(), null, AlertType.ERROR);
                    Display.getDisplay(host).setCurrent(alert);
                }
            } else {
                meetDate.setDate(defaults.getMeetDate());
                meetName.setString(defaults.getMeetName());
            }
            defaultEventNames = defaults.getEvents();
            eventCountField.setString(String.valueOf(defaults.numberOfEvents()));
            defaultTeams = defaults.teams();
        } catch (RecordStoreNotFoundException nf) {
            // do nothing
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
        setEventLabels();
    }

    private void setEventLabels() {
        int events = 0;
        try {
            events = Integer.parseInt(eventCountField.getString());

            if (events < fields) {
                for (int i = events; i < fields; i++) {
                    delete(events + 3);
                }
            } else {
                for (int i = fields; i < events; i++) {
                    append(new TextField("Event " + (i + 1) + " name ",
                            (i < defaultEventNames.length) ? defaultEventNames[i] : "",
                            4, TextField.ANY));
                }
            }
            fields = size() - 3; // number of fields on the form - the top three

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    public void commandAction(Command c, Displayable d) {
        if (c == okCommand) {
            String name = meetName.getString();
            // check for existing filename

            String[] recordStores = RecordStore.listRecordStores();
            boolean found = false;
            if (recordStores != null) {
                for (int index = 0; !found && index < recordStores.length; index++) {
                    found = recordStores[index].equals(name);
                }
            }
            if (found) {
                Alert alert = new Alert("File exists", "Do you wish to overwrite " + name + "?", null, AlertType.CONFIRMATION);
                alert.addCommand(alertOverwriteCommand);
                alert.addCommand(alertCancelCommand);
                alert.setCommandListener(this);
                Display.getDisplay(host).setCurrent(alert);
            } else {
                createMeet();
            }
        } else if (c == backCommand) {
            host.mainMenu();
        } else if (c == loadCommand) {
            host.loadMeetData();
        } else if (c == alertOverwriteCommand) {
            if (meetName.getString().length() > 0) {
                try {
                    RecordStore.deleteRecordStore(meetName.getString());
                } catch (Exception e) {
                    // eat it
                }
                createMeet();
            }
        } else if (c == alertCancelCommand) {
            Display.getDisplay(host).setCurrent(this);
        }

    }
}
